/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package person.document;

import java.io.*;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.el.ELContext;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.model.UploadedFile;
import system.general.*;

/**
 *
 * @author emojica
 */
@ManagedBean(name = "person_document")
@ViewScoped
public class Main extends Beans implements Serializable {

    Logged logged;
    private Persistencia persistencia = new Persistencia();
    private Message msg = new Message();
    private Path path = new Path();
    private Find personal_documentFind = new Find();
    private List<Beans> personal_documentList = new ArrayList<>();
    private String sql;
    private Map<String, String> map = new LinkedHashMap<>();
    private UploadedFile file;

    public Main() {
        ELContext elContext = FacesContext.getCurrentInstance().getELContext();
        logged = (Logged) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "logged");
    }

    private void load() {
        try {
            map.clear();
            map.put("id = " + logged.getDetailId(), " ");

            personal_documentList.clear();
            personal_documentList = personal_documentFind.byMap(map);

            setId(personal_documentList.get(0).getId());
            setId_persona(personal_documentList.get(0).getId_persona());
            setIdl_tipo(personal_documentList.get(0).getIdl_tipo());
            setDetalle(personal_documentList.get(0).getDetalle());
            setArchivo(personal_documentList.get(0).getArchivo());

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void insert() {
        try {

            //Verifica si se ha seleccionado un registro
            if (logged.getMasterId() == 0) {
                throw new Exc("m21");
            }
            if (file == null) {
                throw new Exc("m24");
            }
            map.clear();
            map.put("id_persona = " + logged.getMasterId(), " AND ");
            map.put("idl_tipo = " + getIdl_tipo(), " AND ");
            map.put("lower(detalle) = '" + getDetalle().toLowerCase() + "'", " ");

            //Verifica si el registro existe, de lo contrario lo inserta
            if (personal_documentFind.byExist(map)) {
                throw new Exc("m5");
            }

            sql = "INSERT INTO public.persona_documento (id_persona, idl_tipo, detalle, archivo) "
                    + "VALUES (" + logged.getMasterId() + ", " + getIdl_tipo() + ",  '" + getDetalle() + "', '" + getArchivo() + "' )";

            //Inserta la información del registro
            persistencia.executeUpdate(sql);

            //Localiza el id del registro recien insertado, con la llave única
            personal_documentList = personal_documentFind.byMap(map);

            //Asigna el id del registro insertado a la variable global
            logged.setDetailId(personal_documentList.get(0).getId());

            sql = "UPDATE public.persona_documento SET "
                    + "archivo='" + upLoad() + "' "
                    + "WHERE id =" + logged.getDetailId();

            //Actualiza la información del nombre de archivo
            persistencia.executeUpdate(sql);

            throw new Exc("m1");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void update() {
        try {

            if (logged.getMasterId() == 0) {
                throw new Exc("m4");
            }
            //Verifica si hay registros seleccionados
            if (logged.getDetailId() == 0) {
                throw new Exc("m6");
            }

            //Verifica si el registro existe, de lo contrario lo inserta
            map.clear();
            map.put("id <> " + logged.getDetailId(), " AND ");
            map.put("id_persona = " + logged.getMasterId(), " AND ");
            map.put("idl_tipo = " + getIdl_tipo(), " AND ");
            map.put("lower(detalle) = '" + getDetalle().toLowerCase() + "'", " ");


            if (personal_documentFind.byExist(map)) {
                throw new Exc("m5");
            }

            if (file == null) {
                sql = "UPDATE public.persona_documento SET "
                        + "id_persona = " + logged.getMasterId() + ", "
                        + "idl_tipo = " + getIdl_tipo() + ", "
                        + "detalle = '" + getDetalle() + "' "
                        + "WHERE id = " + logged.getDetailId();
            } else {
                upLoad();
                sql = "UPDATE public.persona_documento SET "
                        + "id_persona = " + logged.getMasterId() + ", "
                        + "idl_tipo= " + getIdl_tipo() + ", "
                        + "detalle='" + getDetalle() + "'"
                        + "archivo='" + getArchivo() + "' "
                        + "WHERE id =" + logged.getDetailId();
            }
            //Actualiza la información del registro
            persistencia.executeUpdate(sql);
            throw new Exc("m2");
        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void delete() {
        try {

            //Verifica si hay registros seleccionados
            if (logged.getDetailId() == 0) {
                throw new Exc("m4");
            }

            //Elimina el resgistro por el id_persona
            deleteById(logged.getDetailId());

            throw new Exc("m3");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void deleteById(int id) throws Exc, SQLException, Exception {
        //Verifica si el usuario ya existe para otra persona
        sql = "DELETE FROM public.persona_documento "
                + "WHERE id = " + id;
        persistencia.executeUpdate(sql);
        File f = new File(path.getPersonPath() + getArchivo());
        File e = new File(path.getPerfilPath() + getArchivo());
        f.delete();
        e.delete();
        clear();
    }

    private String upLoad() {
        try {
            int pointPosition = file.getFileName().lastIndexOf(".");
            int lengthFileName = file.getFileName().length();
            String fileExtention = file.getFileName().substring(pointPosition + 1, lengthFileName);
            String fileName;
            FileOutputStream fOut = null;
            if (getIdl_tipo() != 6) {
                fileName = "persona_" + String.valueOf(logged.getMasterId()) + "_documento_" + String.valueOf(logged.getDetailId() + "." + fileExtention);
                fOut = new FileOutputStream(path.getPersonPath() + fileName);

            } else {
                fileName = "perfil_" + String.valueOf(logged.getMasterId()) + "." + fileExtention;
                fOut = new FileOutputStream(path.getPerfilPath() + fileName);
            }

            InputStream fIn = getFile().getInputstream();

            byte data[] = new byte[1024];
            int bRead = -1;
            while ((bRead = fIn.read(data)) != -1) {
                fOut.write(data, 0, bRead);
            }
            fOut.flush();
            fOut.close();
            fOut = null;

            fIn.close();
            fIn = null;
            return fileName;
        } catch (IOException ex) {
            msg.showErr(namePackage(), "java", ex);
            return null;
        }
    }

    public void clear() {
        clearBeans();
        logged.setDetailId(0);
    }

    public void selectedtempId(int tempId) {
        logged.setDetailId(tempId);
        load();
    }

    public UploadedFile getFile() {
        return file;
    }

    public void setFile(UploadedFile file) {
        this.file = file;
    }

    private String namePackage() {
        Package pack = this.getClass().getPackage();
        return pack.getName();
    }
}
